using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MediaPortal.GUI.Library;
using c3o.Framework.Web;
using System.Xml;
using System.Xml.Serialization;

namespace MediaPortal.GUI.Rss
{
    public partial class RssBaseSetupForm : Form
    {
        //private DataTable dt = new DataTable();
		private Opml opml;

		private TreeNode tvRss;
		private TreeNode tvOpml;
		
		private string Folder = @"Feeds\";
		protected string RssFile = "Feeds.rss.xml";
		protected string OpmlFile = "Feeds.opml.xml";

		public RssBaseSetupForm()
		{
			InitializeComponent();


		}


		private void button1_Click(object sender, EventArgs e)
        {
			// Save General Settings
            this.SaveSettings();

			this.Visible = false;
        }


		private void SaveSettings(TreeNode ParentNode, string FileName)
		{
			// Delete the file
			if (System.IO.File.Exists(FileName)) System.IO.File.Delete(FileName);

			// Save new file
			if (ParentNode.Nodes != null && ParentNode.Nodes.Count > 0)
			{
				Opml op = new Opml();

				op.head.title = ParentNode.Text;

				foreach (TreeNode tn in ParentNode.Nodes)
				{
					OpmlOutline item = (OpmlOutline)tn.Tag;

					op.body.Add(item);

					if (tn.Nodes != null)
					{
						this.UnloadTree(item, tn.Nodes);
					}
				}

				XmlDocument xml = op.GetXml();

				if (xml != null)
				{
					xml.Save(FileName);
				}
			}
		}
		


        private void SaveSettings()
        {
			// Save Torrent Feeds
			this.SaveSettings(this.tvRss, this.Folder + this.RssFile);

			// Save Opml Feeds
			this.SaveSettings(this.tvOpml, this.Folder + this.OpmlFile);

            MediaPortal.Profile.Settings xmlwriter = new MediaPortal.Profile.Settings("MediaPortal.xml");

			//string SiteList = null;

			//foreach (DataGridViewRow row in this.dgList.Rows)
			//{
			//    string Site = row.Cells["rssName"].Value as string;
			//    string Url = row.Cells["rssURL"].Value as string;
			//    string RssImage = row.Cells["rssImage"].Value as string;

			//    if (Site != null && Site.Length > 0 && Url != null && Url.Length > 0)
			//    {
			//        if (SiteList == null)
			//        {
			//            SiteList = Site;
			//        }
			//        else
			//        {
			//            SiteList += "," + Site;
			//        }

			//        xmlwriter.SetValue("torrents", "Site." + Site + ".url", Url);
			//        xmlwriter.SetValue("torrents", "Site." + Site + ".image", RssImage);
			//    }
			//}

			//if (SiteList != null)
			//{
			//    xmlwriter.SetValue("torrents", "SiteList", SiteList);
			//}
			//else
			//{
			//    xmlwriter.RemoveEntry("torrents", "SiteList");
			//}

			// Clear out old settings
			string RssList = xmlwriter.GetValue("torrents", "SiteList") as string;
			if (RssList != null && RssList.Length > 0)
			{
				string[] List = RssList.Split(',');

				foreach (string Site in List)
				{
					xmlwriter.RemoveEntry("torrents", "Site." + Site + ".url");
					xmlwriter.RemoveEntry("torrents", "Site." + Site + ".image");
				}
				xmlwriter.RemoveEntry("torrents", "SiteList");
			}
        }

        private void LoadSettings()
        {
            MediaPortal.Profile.Settings xmlreader = new MediaPortal.Profile.Settings("MediaPortal.xml");

            //if (this.tbxPath.Text == null || this.tbxPath.Text.Length == 0)
            //{
                //this.tbxPath.Text = @"c:\temp";
            //}

			string RssList = xmlreader.GetValue("torrents", "SiteList") as string;

			if (RssList != null && RssList.Length > 0)
			{
			    //dt.Columns.Add("RssName");
			    //dt.Columns.Add("RssURL");
			    //dt.Columns.Add("RssImage");

			    string[] List = RssList.Split(',');

			    foreach (string Site in List)
			    {
			        //DataRow row = dt.NewRow();
			        //row["RssName"] = Site;

			        string URL = xmlreader.GetValue("torrents", "Site." + Site + ".url") as string;
			        string RssImage = xmlreader.GetValue("torrents", "Site." + Site + ".image") as string;

			        //row["rssURL"] = URL;
			        //row["rssImage"] = RssImage;

			        //dt.Rows.Add(row);

			        // Add Tree Node
			        TreeNode tn = new TreeNode(Site);
			        OpmlOutline outline = new OpmlOutline(Site, "link", URL, RssImage, null, null);
			        tn.Tag = outline;

			        this.tvRss.Nodes.Add(tn);
			    }

               // this.dgList.DataSource = dt;
            }
        }

		private void LoadSettings(TreeNode ParentTree, string FileName)
		{
			if(System.IO.File.Exists(FileName))
			{
				XmlDocument xml = new XmlDocument();
				xml.Load(FileName);
				opml = new Opml(xml);
				this.LoadTree(ParentTree, opml.body.outlines);
			}
		}


		private void LoadTree(TreeNode parent, OpmlOutline[] list)
		{
			foreach (OpmlOutline item in list)
			{
				TreeNode tn = new TreeNode(item.text);
				tn.Tag = item;

				parent.Nodes.Add(tn);

				if (item.outlines != null)
				{
					this.LoadTree(tn, item.outlines);
				}
			}
		}

		private void UnloadTree(OpmlOutline parent, TreeNodeCollection list)
		{
			foreach (TreeNode tn in list)
			{
				OpmlOutline item = (OpmlOutline)tn.Tag;

				parent.Add(item);

				if (tn.Nodes != null)
				{
					this.UnloadTree(item, tn.Nodes);
				}
			}
		}



        private void SetupForm_Load(object sender, EventArgs e)
        {
			if (!System.IO.Directory.Exists("Feeds"))
				System.IO.Directory.CreateDirectory("Feeds");

			this.tvRss = this.tvList.Nodes.Add("Content Feeds (rss)");
			this.tvOpml = this.tvList.Nodes.Add("Search Feeds (opml)");

			this.LoadSettings();

			// Load Torrent Feeds
			this.LoadSettings(this.tvRss, this.Folder + this.RssFile);

			// Load Opml Feeds
			this.LoadSettings(this.tvOpml, this.Folder + this.OpmlFile);

			// Show The Tree
			this.tvList.ExpandAll();

			// Select Feeds
			this.tvList.SelectedNode = this.tvRss;
        }
		


		//private void button2_Click(object sender, EventArgs e)
		//{
		//    //if (this.folderBrowserDialog1.ShowDialog() == DialogResult.OK)
		//    //{
		//        //this.tbxPath.Text = this.folderBrowserDialog1.SelectedPath;
		//    //}
		//}




        private void button1_Click_1(object sender, EventArgs e)
        {
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                this.tbxUrl.Text = this.openFileDialog1.FileName;
            }
        }

        private void bttnAdd_Click_1(object sender, EventArgs e)
        {
			XmlDocument xml = new XmlDocument();
			SiteReader sr = new SiteReader();

			// Read rss feed into XmlDocument
			xml.LoadXml(sr.ReadPage(tbxUrl.Text));

			switch (xml.DocumentElement.Name)
			{
				case "opml":
					//this.AddOpml(xml);
					this.AddOpmlTree(xml);
					break;
				case "rss":
					//this.AddRss(xml);
					this.AddRssTree(xml);
					break;
				default:
					break;
			}

			//RssReader rss = new RssReader(xml);

			//if (rss.Header.Rows.Count > 0)
			//{
			//    DataRow row = this.dt.NewRow();

			//    row["rssName"] = rss.Header.Rows[0]["title"].ToString();
			//    row["rssUrl"] = this.tbxUrl.Text;

			//    //if (rss.Header.Columns.Contains("image"))
			//    //{
			//    //    row["rssImage"] = rss.Header.Rows[0]["image"].ToString();
			//    //}

			//    if (rss.Header.Columns.Contains("itunes:image_href"))
			//    {
			//        row["rssImage"] = rss.Header.Rows[0]["itunes:image_href"].ToString();
			//    }

			//    this.dt.Rows.Add(row);
			//    //this.dgList.Rows.Add(rss.Header.Rows[0]["title"].ToString(), this.tbxUrl.Text);
			//}
        }

		//private void AddOpml(XmlDocument xml)
		//{
		//    Opml opml = new Opml(xml);

		//    DataRow row = this.dt.NewRow();

		//    row["rssName"] = opml.head.title;
		//    row["rssUrl"] = this.tbxUrl.Text;
		//    row["rssImage"] = opml.head["image"];

		//    this.dt.Rows.Add(row);
		//}

		private void AddOpmlTree(XmlDocument xml)
		{
		//	if (this.tvList.SelectedNode != null)
		//	{
				// Read xml
				Opml opml = new Opml(xml);

				// Add Tree Node
				TreeNode tn = new TreeNode(opml.head.title);
				OpmlOutline outline = new OpmlOutline(opml.head.title, "link", this.tbxUrl.Text, opml.head["image"], null, null);
				tn.Tag = outline;

				this.tvOpml.Nodes.Add(tn);

		//		this.tvList.SelectedNode.Nodes.Add(tn);
		//	}
		}



		//private void AddRss(XmlDocument xml)
		//{
		//    RssReader rss = new RssReader(xml);

		//    if (rss.Header.Rows.Count > 0)
		//    {
		//        DataRow row = this.dt.NewRow();

		//        row["rssName"] = rss.Header.Rows[0]["title"].ToString();
		//        row["rssUrl"] = this.tbxUrl.Text;

		//        //if (rss.Header.Columns.Contains("image"))
		//        //{
		//        //    row["rssImage"] = rss.Header.Rows[0]["image"].ToString();
		//        //}

		//        if (rss.Header.Columns.Contains("itunes:image_href"))
		//        {
		//            row["rssImage"] = rss.Header.Rows[0]["itunes:image_href"].ToString();
		//        }

		//        this.dt.Rows.Add(row);
		//        //this.dgList.Rows.Add(rss.Header.Rows[0]["title"].ToString(), this.tbxUrl.Text);			

		//    }
		//}

		private void AddRssTree(XmlDocument xml)
		{
			//if (this.tvList.SelectedNode != null)
			//{
				RssReader rss = new RssReader(xml);

				if (rss.Header.Rows.Count > 0)
				{
					string name = rss.Header.Rows[0]["title"].ToString();
					string url = this.tbxUrl.Text;
					string image = null;

					if (rss.Header.Columns.Contains("itunes:image_href"))
					{
						image = rss.Header.Rows[0]["itunes:image_href"].ToString();
					}

					TreeNode tn = new TreeNode(name);
					OpmlOutline outline = new OpmlOutline(name, "link", url, image, null, null);
					tn.Tag = outline;

					this.tvRss.Nodes.Add(tn);
				}
			//}
		}

		private void tvList_AfterSelect(object sender, TreeViewEventArgs e)
		{
			TreeNode tn = this.tvList.SelectedNode;


			if (tn==null || tn.Tag == null)
			{
				gbDetail.Visible = false;
			}
			else
			{
				gbDetail.Visible = true;

				if (tn != null)
				{
					if (tn.Tag != null)
					{
						OpmlOutline item = (OpmlOutline)tn.Tag;

						this.tbxItemName.Text = item.text;
						this.tbxItemUrl.Text = item.url;
						this.tbxItemImage.Text = item.image;
						this.tbxPattern.Text = item.search;
						this.tbxReplacement.Text = item.replace;
					}
				}
			}
		}

		private void button1_Click_2(object sender, EventArgs e)
		{
			TreeNode tn = this.tvList.SelectedNode;

			if (tn != null)
			{
				if (tn.Tag != null)
				{
					OpmlOutline item = (OpmlOutline)tn.Tag;

					item.text = this.tbxItemName.Text;
					item.url = this.tbxItemUrl.Text;
					item.image = this.tbxItemImage.Text;
					item.search = this.tbxPattern.Text;
					item.replace = this.tbxReplacement.Text;
					
					tn.Text = this.tbxItemName.Text;
					
					tn.Tag = item;
				}
			}
		}

		private void bttnDelete_Click(object sender, EventArgs e)
		{
			TreeNode tn = this.tvList.SelectedNode;

			if (tn != null)
			{
				this.tvList.Nodes.Remove(tn);
			}
		}

		private void tvList_ItemDrag(object sender,	System.Windows.Forms.ItemDragEventArgs e)
		{
			//  Remember the Item being dragged if it is a file node (ImageIndex == 2)
			TreeNode aNode = (TreeNode)e.Item;

			// Only drag if it is a file, where not dragging directories in this example
			if (aNode.Tag != null)
			{
				this.DoDragDrop(aNode, DragDropEffects.Move);
			}
		}


		private void tvList_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
		{
			e.Effect = DragDropEffects.Move;
		}



		private void tvList_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
		{
			TreeNode NewNode;

			if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false))
			{
				Point pt = ((TreeView)sender).PointToClient(new Point(e.X, e.Y));
				TreeNode DestinationNode = ((TreeView)sender).GetNodeAt(pt);

				NewNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");

				if (DestinationNode != NewNode)
				{
					if (NewNode.Parent == DestinationNode) 
					{
						DestinationNode.Nodes.Insert(0, (TreeNode)NewNode.Clone());
						//DestinationNode.Nodes.Add((TreeNode)NewNode.Clone());
						DestinationNode.Expand();
						NewNode.Remove();
					}
					else
					{
						if (NewNode.Parent == DestinationNode.Parent)
						{
							// Insert the node after the one you drop it on
							DestinationNode.Parent.Nodes.Insert(DestinationNode.Index + 1, (TreeNode)NewNode.Clone());

							//DestinationNode.Nodes.Add((TreeNode)NewNode.Clone());

							//DestinationNode.Expand();

							//Remove Original Node
							NewNode.Remove();
						}
					}
				}
			}
		}

		private void bttnAddDetail_Click(object sender, EventArgs e)
		{
			TreeNode tn = this.tvList.SelectedNode;

			if (tn != null)
			{
				OpmlOutline item = new OpmlOutline(this.tbxItemName.Text, "link", this.tbxItemUrl.Text, this.tbxItemImage.Text, this.tbxPattern.Text, this.tbxReplacement.Text, null, null);

				TreeNode newtn = tn.Nodes.Add(this.tbxItemName.Text);

				newtn.Tag = item;
			}
		}

		private void button2_Click(object sender, EventArgs e)
		{
			TreeNode tn = this.tvList.SelectedNode;

			if (tn != null)
			{
				if (tn.Tag != null)
				{
					OpmlOutline outline = (OpmlOutline)tn.Tag as OpmlOutline;

					if (outline != null)
					{
						outline.Delete();						
					}
				}
			}
		}

		private void bttnCancel_Click(object sender, EventArgs e)
		{
			this.Visible = false;
		}	
    }
}